/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *SdProjectTaskFeedbackController
 * 项目任务反馈
 *
 * 修改纪录
 * 2021-01-14 版本：1.0 lanjianwei 创建。
 * @version 版本：1.0
 * @author 作者：lanjianwei
 * 创建日期：2021-01-14
 */

package com.topscomm.gpm.controller;

import com.topscomm.gpm.controller.auto.GpmProjectTaskFeedbackControllerAuto;
import com.topscomm.pub.util.BaseUtil;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.gpm.pojo.GpmProjectTaskEntity;
import com.topscomm.gpm.pojo.GpmProjectTaskFeedbackEntity;
import com.topscomm.gpm.service.impl.GpmProjectTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapApprovalBillStateEnum;

/**
 * @author: lanjianwei
 * @date: 2021-01-14
 * @description:项目任务反馈Controller
 * @modify:
 */
@RestController
@RequestMapping("sd/projectTaskFeedback")
public class GpmProjectTaskFeedbackController extends GpmProjectTaskFeedbackControllerAuto
		implements IGpmProjectTaskFeedbackController {
	@Autowired
    private GpmProjectTaskService gpmProjectTaskService;
	/**
	 * @author: lanjianwei
	 * @date: 2021-01-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_taskid")) {
			String value = paraMap.get("qry_taskid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and taskid = '{0}'", value);
		}
		if (paraMap.containsKey("qry_taskfeedbackdetail")) {
			String value = paraMap.get("qry_taskfeedbackdetail").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and taskfeedbackdetail like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state in ({0})", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		/*
		 * if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限 {
		 * String dataPession = service.getDataPermission(TapOperationTypeEnum.Select,
		 * "", this.getUserBean()); if (StringUtil.isEmpty(dataPession))//
		 * 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据 { String deptcodes_header =
		 * ConvertUtil.convertToString(this.getUserBean().getUser().getValue(
		 * "deptcodes_header")); if (StringUtil.isEmpty(deptcodes_header)) sql.
		 * appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )"
		 * , this.getUserBean().getUser().getCode(),
		 * this.getUserBean().getDept().getCode(), this
		 * .getUserBean().getWorkDept().getCode()); else sql.
		 * appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )"
		 * , deptcodes_header, this.getUserBean().getUser().getCode(), this
		 * .getUserBean().getDept().getCode(),
		 * this.getUserBean().getWorkDept().getCode()); } else// 使用数据权限 {
		 * sql.appendSingle(" and {0} ", dataPession); } }
		 */
		return sql.toString();
	}

	/**
	 * @author: lanjianwei
	 * @date: 2021-01-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: lanjianwei
	 * @date: 2021-01-14
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目任务反馈申请! ", dataMap.get("applydeptname"), dataMap.get("username"),
				DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
		dataMap.put("maintitle", mailtitle.toString());
		// 保存和提交合并成一个按钮，后端提交时存入id
/*		String taskid = String.valueOf(paraMap.get("taskid"));
		String taskfeedbackdetail = (String) paraMap.get("taskfeedbackdetail");
		String taskschedule = String.valueOf(paraMap.get("taskschedule"));
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.appendLineSingle("taskid='{0}' and taskfeedbackdetail = '{1}' and taskschedule = '{2}'", taskid,
				taskfeedbackdetail, taskschedule);
		List<SdProjectTaskFeedbackEntity> sdProjectTaskFeedbackEntities = this.service
				.queryByWhere(whereSql.toString());
		if(sdProjectTaskFeedbackEntities.size()>0) {
			long id = sdProjectTaskFeedbackEntities.get(0).getId();
			dataMap.put("id", id);
		}else {
			throw new ServiceException("提交任务进度更新单据失败（无法获取任务更新单据的id），请联系管理员！");
		}*/

	}


	/**
	 * @author: wudaliang
	 * @date: 2021-03-12
	 * @param: paraMap
	 * @description: 删除已执行的任务时，删除对应的任务反馈
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@DeleteMapping({"/deletecasetask"})
	public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String ids = ConvertUtil.convertToString(paraMap.get("ids"));
			this.service.deleteByWhere(" taskid in (" + ids + ")");
			this.afterDelete(paraMap);
			return ResponseResult.ok("删除成功");
		} catch (Exception var3) {
			return this.handleControllerException(var3);
		}
	}


	/**
	 * @Title: submit
	 * @description: 先保存再提交
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @date: 2021年2月1日上午10:32:57
	 * @modify:
	*/
	@PutMapping(value = "/submit")
	public ResponseResult<Object> submit(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
//			ResponseResult responseResult= this.insert(paraMap);
//			paraMap=(Map) responseResult.getResult();
			Map<String, Object> dataMap = paraMap;
			paraMap.put("submitdate", new Date());
			beforeSubmit(dataMap, paraMap);
			String mailTitle = "";
			if (dataMap.containsKey("maintitle")) {
				mailTitle = ConvertUtil.convertToString(dataMap.get("maintitle"));
			}
			GpmProjectTaskFeedbackEntity gpmProjectTaskFeedbackEntity = this.service.queryById(ConvertUtil.convertToString(dataMap.get("id")));
			if (gpmProjectTaskFeedbackEntity == null) {
				Class<GpmProjectTaskFeedbackEntity> entityClass = this.entityClass;
				gpmProjectTaskFeedbackEntity = entityClass.newInstance();
			}
			// 处于审批中和已审批的单据不能再提交审批
			if (TapApprovalBillStateEnum.Approveing == ConvertUtil.convertToInt(gpmProjectTaskFeedbackEntity.getState())
					|| TapApprovalBillStateEnum.Approved == ConvertUtil.convertToInt(gpmProjectTaskFeedbackEntity.getState()))
				return ResponseResult.error("不是退回和开立的单据不能提交审批");
			for (Object key : dataMap.keySet()) {
				String tempKey = ConvertUtil.convertToString(key);
				gpmProjectTaskFeedbackEntity.setValue(tempKey, dataMap.get(key));
			}
			this.service.executeSubmit(gpmProjectTaskFeedbackEntity, mailTitle, this.getUserBean());
			dataMap = this.service.queryMapById(ConvertUtil.convertToString(dataMap.get("id")));
			// 增加前台待审批消息提醒
			afterSubmit(dataMap, paraMap);
			return ResponseResult.ok("提交成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

    /**
     * @description: 手机端提交审批接口
     * @param: param
     * @return:
     * @author hdy
     * @date: 2021/12/27
     */
	   @GetMapping("/mobileSubmit")
	    public ResponseResult<Object> mobileSubmit(@RequestParam(required = false) Map<String, Object> param) {

	    	if(param.containsKey("taskid")) {
	    		StringBufferProxy sql = new StringBufferProxy();
	    		GpmProjectTaskEntity gpmProjectTaskEntity =  gpmProjectTaskService.queryById(ConvertUtil.convertToString(param.get("taskid")));
	            param.put("planstartdate", gpmProjectTaskEntity.getPlanstartdate());
	            param.put("planenddate", gpmProjectTaskEntity.getPlanenddate());
	            param.put("taskdistributedate", gpmProjectTaskEntity.getTaskdistributedate());
	            param.put("flowid", flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_GpmProjectTaskFeedback", this.getUserBean(), "sortcode").get(0).get("id"));
	            if (param.containsKey("id")) {
	                this.update(param);
	                this.submit(param);
	                return ResponseResult.ok("操作成功");
	            } else {
	            	try {
	                    long[] arrayId = PrimaryKeyUtil.GeneIDs(GpmProjectTaskFeedbackEntity.tableName, 1);
	                    param.put("id", arrayId[0]);
	            		this.insert(param);
	                    this.submit(param);
	                    return ResponseResult.ok("操作成功");
	                } catch (Exception ex) {
	                	return handleControllerException(ex);
	                }
	            }
	    	} else {
	    		  this.update(param);
	              this.submit(param);
	              return ResponseResult.ok("操作成功");
	    	}

	    }
}
